`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    14:50:42 03/30/2013 
// Design Name: 
// Module Name:    clock_divider 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module clock_divider(
    input Sys_clk_100mhz,
	 input rst,
    output clk_50mhz
    );
	 
	 // a parameter to set the counter width
	 parameter width = 22;
	 // counter will incremement until a value of division - 1 is met.
	 reg [width:0] counter = 1'b0;
	 // a parameter to divide the clock by 2 * division
	 parameter division = 1;
	 // output 
	 reg out = 1'b1;
	 // this register was added as a failsafe. I noticed when testing that
	 // if the reset was set in a certain way, then the clock divider was 
	 // always off by one cyclce on its first positive edge
//	 reg idle = 1'b0;
	 // asynchronous reset
	 always @(negedge rst or posedge Sys_clk_100mhz) begin
		if (~rst) begin
			counter <= 1'b0;
			out <= 1'b0;
//			idle <= 1'b0;
		end
		else
			// checks to see if  the counter has reached the division value - 1
			// resets the counter and changes the output.
			if (counter >= division - 1'b1) begin
				counter <= 1'b0;
				out <= ~out;
			end
//			else begin
				// ensures that no glitch is possible with reset. If the machine
				// is not in idle, then the counter will incrememnt.
//				if (~idle) begin
//					idle <= 1'b1;
//					counter <= 1'b0;
//				end
				else
					counter <= counter + 1'b1;
//			end
		end
		
	 assign clk_50mhz = out;
endmodule
